<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="等级名称" prop="levelName">
        <el-input
          v-model="queryParams.levelName"
          placeholder="请输入等级名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:level:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:level:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:level:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:level:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="levelList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="等级名称" align="center" prop="levelName" />
      <el-table-column label="等级唯一标识" align="center" prop="levelCode" />
      <el-table-column
        label="下级"
        align="center"
        prop="nextLevelInfo.levelName"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:level:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:level:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改等级对话框 -->
    <el-dialog :title="title" v-model="open" width="80%" append-to-body>
      <el-form ref="levelRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="等级名称" prop="levelName">
              <el-input v-model="form.levelName" placeholder="请输入等级名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="等级唯一标识"
              prop="levelCode"
              label-width="120px"
            >
              <el-input
                v-model="form.levelCode"
                placeholder="请输入等级唯一标识"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下级主键" prop="nextLevelId">
              <el-select
                v-model="form.nextLevelId"
                placeholder="请选择下级主键"
              >
                <el-option
                  v-for="item in levelList"
                  :key="item.levelId"
                  :label="item.levelName"
                  :value="item.levelId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="等级类型" prop="levelType">
              <el-select v-model="form.levelType" placeholder="请选择等级类型">
                <el-option
                  v-for="item in levelTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="签到赠送消费金数量"
              prop="signSendAmount"
              label-width="140px"
            >
              <el-input
                v-model="form.signSendAmount"
                placeholder="请输入签到赠送消费金数量"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="单次消费消费金使用比例"
              prop="paymentUseRate"
              label-width="170px"
            >
              <el-input
                v-model="form.paymentUseRate"
                placeholder="请输入单次消费消费金使用比例"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="金积分释放比例"
              prop="releaseFlashRate"
              label-width="140px"
            >
              <el-input
                v-model="form.releaseFlashRate"
                placeholder="请输入金积分释放比例"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="金积分释放金豆比例（剩余为功德金）"
              prop="releaseAmountRate"
              label-width="250px"
            >
              <el-input
                v-model="form.releaseAmountRate"
                placeholder="请输入金积分释放金豆比例（剩余为功德金）"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="全网手续费加权分红比例"
              prop="serviceShareRate"
              label-width="170px"
            >
              <el-input
                v-model="form.serviceShareRate"
                placeholder="请输入全网手续费加权分红比例"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="团队加速金积分释放比例"
              prop="teamReleaseFlashRate"
              label-width="170px"
            >
              <el-input
                v-model="form.teamReleaseFlashRate"
                placeholder="请输入团队加速金积分释放比例"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="平级加速金积分释放比例"
              prop="sameLevelRate"
              label-width="170px"
            >
              <el-input
                v-model="form.sameLevelRate"
                placeholder="请输入平级加速金积分释放比例"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="邀请用户赠送消费金"
              prop="shareSendAmount"
              label-width="170px"
            >
              <el-input
                v-model="form.shareSendAmount"
                placeholder="请输入邀请用户赠送消费金"
                type="number"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <h2>升级条件</h2>

        <el-row :gutter="10">
          <el-col :span="8" v-if="form.levelType == 4 || form.levelType == 1">
            <el-form-item label="关联商品" prop="spuId" label-width="100px">
              <el-select
                v-model="form.spuId"
                filterable
                remote
                reserve-keyword
                placeholder="请搜索商品名选择商品"
                :remote-method="getMallSpuListData"
              >
                <el-option
                  v-for="item in mallSpuList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="累计消费天数"
              prop="paymentDays"
              label-width="100px"
            >
              <el-input
                v-model="form.paymentDays"
                placeholder="请输入累计消费天数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="累计消费金额"
              prop="paymentTotalAmount"
              label-width="100px"
            >
              <el-input
                v-model="form.paymentTotalAmount"
                placeholder="请输入累计消费金额"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="直推用户数量"
              prop="directUserNum"
              label-width="100px"
            >
              <el-input
                v-model="form.directUserNum"
                placeholder="请输入直推用户数量"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="直推用户等级"
              prop="directUserLevel"
              label-width="100px"
            >
              <el-select
                v-model="form.directUserLevel"
                placeholder="请选择直推用户等级"
              >
                <el-option
                  v-for="item in levelList"
                  :key="item.levelId"
                  :label="item.levelName"
                  :value="item.levelId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业绩" prop="totalAchievement">
              <el-input
                v-model="form.totalAchievement"
                placeholder="请输入业绩"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="等级详细信息" prop="detail" label-width="110px">
          <el-input
            v-model="form.detail"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Level">
import {
  listLevel,
  getLevel,
  delLevel,
  addLevel,
  updateLevel,
  getMallSpuList,
} from "@/api/system/level";

const { proxy } = getCurrentInstance();

const levelList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    levelName: null,
    levelCode: null,
    nextLevelId: null,
    detail: null,
  },
  rules: {
    levelName: {
      required: true,
      message: "等级名称不能为空",
      trigger: "blur",
    },
    levelCode: {
      required: true,
      message: "等级唯一标识不能为空",
      trigger: "blur",
    },
  },
});

const { queryParams, form, rules } = toRefs(data);

const mallSpuList = ref([]);

// 获取商品列表
function getMallSpuListData(name = "") {
  getMallSpuList({
    name,
  }).then((response) => {
    mallSpuList.value = response.data;
  });
}
getMallSpuListData();
/** 查询等级列表 */
function getList() {
  loading.value = true;
  listLevel(queryParams.value).then((response) => {
    levelList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

const levelTypeList = ref([
  {
    label: "个人",
    value: 1,
  },
  {
    label: "团队",
    value: 2,
  },
  {
    label: "联创",
    value: 3,
  },
  {
    label: "达人",
    value: 4,
  },
  {
    label: "合伙人",
    value: 5,
  },
]);

// 表单重置
function reset() {
  form.value = {
    levelId: null,
    levelName: null,
    levelCode: null,
    nextLevelId: null,
    detail: null,
    levelType: 1,
    signSendAmount: null,
    paymentUseRate: null,
    releaseFlashRate: null,
    releaseAmountRate: null,
    serviceShareRate: null,
    teamReleaseFlashRate: null,
    sameLevelRate: null,
    paymentDays: null,
    paymentTotalAmount: null,
    directUserNum: null,
    directUserLevel: null,
    totalAchievement: null,
    shareSendAmount: null,
    spuId: null,
  };
  proxy.resetForm("levelRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.levelId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加等级";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _levelId = row.levelId || ids.value;
  getLevel(_levelId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改等级";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["levelRef"].validate((valid) => {
    if (valid) {
      form.value.directUserNum = Number(form.value.directUserNum);
      if (form.value.levelId != null) {
        updateLevel(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLevel(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _levelIds = row.levelId || ids.value;
  proxy.$modal
    .confirm('是否确认删除等级编号为"' + _levelIds + '"的数据项？')
    .then(function () {
      return delLevel(_levelIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/level/export",
    {
      ...queryParams.value,
    },
    `level_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
